﻿using AutoMapper;
using MediatR;
using SC.GirdManage.Common;
using SC.GirdManage.Repository;
using SC.GridManage.Domain.Models;
using SC.GridManage.MN.API.Write.Application.Command.Artical;
using Yitter.IdGenerator;

namespace SC.GridManage.MN.API.Write.Application.Handler.Artical
{
    public class UpdateAriticalHandler : IRequestHandler<UpdateAriticalCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ArticalModel> articalRepo;
        private readonly ILogger<UpdateAriticalHandler> logger;
        private readonly IMapper mapper;

        public UpdateAriticalHandler(IBaseRepository<ArticalModel> articalRepo, ILogger<UpdateAriticalHandler> logger,IMapper mapper)
        {
            this.articalRepo = articalRepo;
            this.logger = logger;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(UpdateAriticalCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model = articalRepo.GetModelAsync(request.Id).Result;

             model = mapper.Map(request, model);//映射

            model.UpdateTime = DateTime.Now;

            int r = articalRepo.UpdateAsync(model).Result;
            if (r > 0)
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Success;
                result.Msg = "修改文章成功!";
                result.Data = r;
            }
            else
            {
                result.Code = GirdManage.Common.Enums.EnumResultCode.Fail;
                result.Msg = "修改文章失败!";
                result.Data = r;
            }

            return Task.FromResult(result);
        }
    }
}
